/**
 * 
 */
package com.tvshows.structure.bdd;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * @author tangi
 */
public class HibernateUtil
{

    private SessionFactory sf = null;

    /**
     * @return the session
     */
    public Session getSession()
    {
        if ( sf == null )
        {
            createSessionFactory();
        }

        return sf.openSession();
    }

    /**
     * Creates the configuration to init the session
     */
    @SuppressWarnings( "deprecation" )
    private void createSessionFactory()
    {
        try
        {
            Configuration config = new Configuration();
            config.configure();
            sf = config.buildSessionFactory();
        }
        catch ( Exception ex )
        {
            System.err.println( "Initial SessionFactory creation failed." + ex );
            throw new ExceptionInInitializerError( ex );
        }

    }

    /**
     * Closes the connection
     * 
     * @param transaction current transaction
     * @param session current session
     */
    public void closeConnection( Transaction transaction, Session session )
    {
        transaction.commit();
        session.close();
    }

}
